import axios from 'axios'
import { message } from 'antd'
import { setToken, setUserInfo, clearWindow } from '@redux/actions'
import store from '@redux/store'
import { history } from '@router/Routers'

let errorNoticing = false

const instance = axios.create({
  headers: {
    'Content-Type': 'application/json'
  },
  timeout: 1000 * 120
})

/**
 * 请求方法
 * @param {*} type 请求类型
 */
function request (type) {
  return function (url, params = {}, config = {}) {
    const { basic } = store.getState()
    const { token, userInfo } = basic
    instance.defaults.headers.Authorization = `Bearer ${token}`
    const that = this
    const data = {
      uid: userInfo.id
    }
    if (!token) {
      if (window.location.hash !== '#/login') {
        history.push('/login')
      } else {
        window.location.reload()
      }
      return Promise.reject(new Error('token 不存在'))
    }
    if (type === 'post' || type === 'put') {
      if (params instanceof FormData) {
        config = { ...config, params: { ...config.params, uid: userInfo.id } }
      } else {
        params = Object.assign(params, data)
      }
    } else if (params.params) {
      params = { params: Object.assign(params.params, data) }
    } else {
      params = { params: Object.assign(params, data) }
    }
    return new Promise((resolve, reject) => {
      instance[type](url, params, config)
        .then(res => {
          resolve(res.data)
        })
        .catch(e => {
          console.error(e)
          const { basic } = store.getState()
          const { status, data } = e.response || { status: 504, data: { message: '网络错误' } }
          if (basic.token === '') {
            if (history.location.pathname !== '/login') {
              store.dispatch(clearWindow())
              history.push('/login')
            }
            return reject(e)
          }
          if (status === 401 || (status === 500 && data.message === '登录超时')) {
            if (!basic.token) {
              return reject(e)
            }
            store.dispatch(setToken(''))
            store.dispatch(setUserInfo({}))
            store.dispatch(clearWindow())
            that && that.props.setToken(undefined)
            if (!errorNoticing) {
              errorNoticing = true
              message.error(token ? '登录超时' : '请先登录', 2, () => {
                errorNoticing = false
              })
            }
            setTimeout(() => {
              history ? history.push('/login') : location.reload()
            }, 2000)
            return reject(e)
          }
          if (status === 504 && !errorNoticing) {
            errorNoticing = true
            message.error('网络异常', 2, () => { errorNoticing = false })
          } else {
            message.error(data.message, 2)
          }
          reject(e)
        })
    })
  }
}

export const $get = request('get')
export const $delete = request('delete')
export const $post = request('post')
export const $put = request('put')
